﻿#include "TcpClient.h"
#include <QRegularExpression>

#pragma execution_character_set("utf-8")

TcpClient::TcpClient(QObject *parent) : ComBase(parent)
{
    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
    mTcpSocket = new QTcpSocket(this);//初始化socket
    connect(mTcpSocket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
#if QT_VERSION >= 0x060000
// Qt 6 的代码
    connect(mTcpSocket, &QAbstractSocket::errorOccurred, this, &TcpClient::onErrorOccurred);
#else
    // Qt 5 的代码
    connect(mTcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &TcpClient::onErrorOccurred);
#endif
    connect(mTcpSocket, &QTcpSocket::stateChanged, this, &TcpClient::onStateChanged);

    mReconnectTimer = new QTimer(this);
    connect(mReconnectTimer, &QTimer::timeout, this, &TcpClient::onInit);
}

void TcpClient::onInit()
{
    if(mTcpSocket == nullptr){
        qDebug() << "Tcp not init!";
    }
    mTcpSocket->connectToHost(mConfig.tcp.mOpponentIP,mConfig.tcp.mOpponentPort);
    if (mTcpSocket->waitForConnected(500)){
        setState(CS_Connected);
    }
}

void TcpClient::onQuit()
{
    disconnect();
    if(mTcpSocket != nullptr){
        delete  mTcpSocket;
        mTcpSocket = nullptr;
    }
    if(mReconnectTimer){
        delete mReconnectTimer;
        mReconnectTimer = nullptr;
    }
    deleteLater();
}
void TcpClient::disconnect()
{
    if(mTcpSocket->state() == QAbstractSocket::SocketState::ConnectedState){
        mTcpSocket->disconnectFromHost();
        if(mTcpSocket->state() != QAbstractSocket::SocketState::UnconnectedState){
            mTcpSocket->waitForDisconnected(10);
        }
    }
}

void TcpClient::onErrorOccurred(QAbstractSocket::SocketError socketError)
{
    QString errStr = QString("error Occurred, errCode: %1, errString: %2").arg(socketError).arg(mTcpSocket->errorString());
    emit sigMsg(errStr);
}

void TcpClient::onStateChanged(QAbstractSocket::SocketState socketState)
{
    if(socketState == QAbstractSocket::SocketState::UnconnectedState){
        setState(CS_UnConnected);
        if(mIsEnableReconnect){
            mReconnectTimer->start(2000);
        }
    } else {
        mReconnectTimer->stop();
        if(socketState == QAbstractSocket::SocketState::ConnectedState){
            setState(CS_Connected);
        }
    }
}

void TcpClient::onReadyRead()
{
    QByteArray datagram;
    datagram = mTcpSocket->readAll();;
    if(datagram.size() < 1)
        return;
    emit sigReceiveData(datagram);
    processData(datagram);
}

void TcpClient::writeData(const QByteArray& data)
{
    qint64 reply = mTcpSocket->write(data);
    if(reply == -1){
        emit sigMsg(tr("<font color=\'red\'>发送失败:</font>") + mTcpSocket->errorString());
    }
}
void TcpClient::processData(const QByteArray &data)
{

}

